package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.info.DataPackageInfo;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public final class DataPackageParser {
    private static final String MODULE_JSON_FILE = "modules.json";

    /**
     * 解析压缩包中的模块信息
     * @param zipStream 压缩包输入流
     * @return 标准化数据包信息
     * @throws
     */
    public static DataPackageInfo parse(InputStream zipStream) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(zipStream)) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (MODULE_JSON_FILE.equals(entry.getName())) {
                    String jsonStr = IOUtils.toString(zis, StandardCharsets.UTF_8);
                    return parseToDataPackageInfo(jsonStr);
                }
            }
            throw new IllegalArgumentException("压缩包中未找到 " + MODULE_JSON_FILE);
        }
    }

    private static DataPackageInfo parseToDataPackageInfo(String jsonStr) {
        JSONObject root = JSON.parseObject(jsonStr);
        DataPackageInfo info = new DataPackageInfo();

        // 解析基础信息
        JSONObject app = root.getJSONObject("app");
        info.setBundleName(app.getString("bundleName"));
        info.setVendor(app.getString("vendor"));

        // 处理版本信息
        JSONObject version = app.getJSONObject("version");
        info.setVersionCode(version.getString("code"));
        info.setVersionCodeNum( version.getString("name"));

        return info;
    }


}
